package com.holystone.splunk.utils;

import java.util.Calendar;
import java.util.Date;

/**
 * Copyright (c) 2017, HOLYSTONE Technologies, Inc.
 * All right reserved.
 *
 * @author huyan
 * @date 2017/10/23
 * @desc: 日历工具类
 */
public class CalendarUtils {

    /**
     * 计算当前日期的前/后天数
     * @param flag
     *    true：计算当前日期之后的天数
     *    false：计算当前日期之前的天数
     * @param flagDays
     *    天数限定
     * @return
     */
    public static Date getDateByDays(Boolean flag, Integer flagDays) {
        if (flagDays == null) {
            return null;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        if (flag) {
            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) + flagDays);
        }else {
            calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - flagDays);
        }
        return calendar.getTime();
    }

    /**
     * 计算两个日期的差值
     * @param earliest
     * @param latest
     * @return
     */
    public static Long getDistanceDays(Date earliest, Date latest) {
        if (earliest == null || latest == null) {
            return -1L;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(earliest);
        Long start = calendar.getTimeInMillis();
        calendar.setTime(latest);
        Long end = calendar.getTimeInMillis();
        return (end - start) / 1000 / 3600 / 24;
    }
}
